﻿#region License
/*

	Copyright (C) 2008 Oliver Charles, Daniel Hollander

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
*/
#endregion

using System;
using System.Collections.Generic;
using Moebius.Core;
using Moebius.Profiling;

namespace Moebius.Profiling
{
    public static class Profiler
    {
        public static ProfileResults Profile(Action<int> profileAction)
        {
            return Profile(profileAction, 10, 10000, 10, 3);
        }

        public static ProfileResults Profile(Action<int> toProfile, int minIterations,
                                      int maxIterations, int increment, int avergaes)
        {
            Stopwatch iterationTimer = new Stopwatch();
            List<ProfileIteration> profileIterations = new List<ProfileIteration>();

            for (int iterations = minIterations; iterations < maxIterations; iterations += increment)
            {
                double iterationRunTime = 0;
                for (int run = 0; run < avergaes; run++)
                {
                    iterationTimer.Reset();

                    for (int i = 0; i < iterations; i++)
                        toProfile(i);

                    iterationRunTime += iterationTimer.Lap();
                }

                ProfileIteration pIteration = new ProfileIteration(iterations, iterationRunTime / avergaes);
                profileIterations.Add(pIteration);
            }

            ProfileResults results = new ProfileResults(profileIterations);

            return results;
        }
    }
}